package com.eagle.web.config;

import com.eagle.web.http.converter.properties.MappingProperties2HttpMessageConverter;
import com.eagle.web.method.support.PropertiesHandlerMethodReturnValueHandler;
import com.eagle.web.support.impl.PropertiesHandlerMethodArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class RestWebMvcConfigurer implements WebMvcConfigurer {

	@Autowired
	private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

	@PostConstruct
	public void init(){
		List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();
		List<HandlerMethodArgumentResolver> newArgumentResolvers = new ArrayList<>(argumentResolvers.size()+1);

		newArgumentResolvers.add(new PropertiesHandlerMethodArgumentResolver());
		newArgumentResolvers.addAll(argumentResolvers);
		requestMappingHandlerAdapter.setArgumentResolvers(newArgumentResolvers);

		List<HandlerMethodReturnValueHandler> returnValueHandlers = requestMappingHandlerAdapter.getReturnValueHandlers();
		List<HandlerMethodReturnValueHandler> newReturnValueHandlers = new ArrayList<>(returnValueHandlers.size()+1);
		newReturnValueHandlers.add(new PropertiesHandlerMethodReturnValueHandler());
		newReturnValueHandlers.addAll(returnValueHandlers);
		requestMappingHandlerAdapter.setReturnValueHandlers(newReturnValueHandlers);
	}

	public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
//		converters.add(new MappingProperties2HttpMessageConverter());
		converters.set(0,new MappingProperties2HttpMessageConverter());
	}


}
